import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/**
 *
 * @ProjectName:    sk_base
 * @Package:        widget
 * @ClassName:      base_widget
 * @Description:    基础状态组件
 * @Author:         孙浩
 * @CreateDate:     5/22/21 1:55 PM
 */

abstract class SKBaseState<T extends StatefulWidget> extends State<T> {
  PageStatus _status = PageStatus.showView;
  String pageTitle;
  StreamController<PageStatus> _streamController = StreamController();

  @override
  void initState() {
    super.initState();
    pageTitle = setPageTitle();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<PageStatus>(
      builder: (ctx, snapshort) {
        Widget result;

        switch (snapshort.data) {
          case PageStatus.loading:
            result = buildLoading(context);
            break;
          case PageStatus.error:
            result = buildError(context);
            break;
          case PageStatus.showView:
            result = buildView(context);
            break;
        }
        return result;
      },
      stream: _streamController.stream,
      initialData: _status,
    );
  }

  Widget buildView(BuildContext context);

  Widget buildError(BuildContext context) {
    return EasyStateView(
        child: Center(child: Text("加载错误请重试")), title: pageTitle ?? "");
  }

  Widget buildLoading(BuildContext context) {
    return EasyStateView(
        child: Center(
          child: Container(
            height: 40,
            width: 40,
            child: CircularProgressIndicator(),
          ),
        ),
        title: pageTitle ?? "");
  }

  beginLoading() {
    _status = PageStatus.loading;
    _streamController.add(_status);
  }

  loadingComplete() {
    _status = PageStatus.showView;
    _streamController.add(_status);
  }

  loadingError() {
    _status = PageStatus.error;
    _streamController.add(_status);
  }

  String setPageTitle();

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }
}

enum PageStatus {
  loading,
  error,
  showView,
}

class EasyStateView extends StatelessWidget {
  final Widget child;
  final String title;

  EasyStateView({@required this.child, @required this.title});

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: child,
      );
}
